//
//  GridViewViewController.m
//  DemoMeshtiles
//
//  Created by MAC on 7/18/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "GridViewViewController.h"
#import "CustomGridCell.h"
#import "SBJsonParser.h"
#import "EGOCache.h"

@interface GridViewViewController ()
@property (nonatomic) BOOL isParseJSON;
@property (nonatomic) BOOL isLoadingDataNextPage;
@end
NSMutableArray *photoStreams;
@implementation GridViewViewController
@synthesize isLoadSucces;
@synthesize isParseJSON;
@synthesize currPage=_currPage;
@synthesize userId=_userId;
@synthesize tag=_tag;
@synthesize isLoadingDataNextPage=_isLoadingDataNextPage;
@synthesize detailView;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
        
    }
    NSLog(@"Chay vao intiWithStyle");
    
    
    return self;
}
-(NSString *)generateURLFromUserId:(NSString *)userIdentifier tag:(NSString *)tag_f page:(NSInteger)currentPage {
    NSString *result=[[[NSString alloc] initWithFormat:@"http://ec2-107-20-246-0.compute-1.amazonaws.com/api/View/getListPhotoByTags?user_id=%@&tag=%@&page_index=%i",userIdentifier,tag_f,currentPage] autorelease];
    
    return result;
}
- (void)viewDidLoad
{
    [super viewDidLoad];   
    tagSetting=@"cat";
    isChange=YES;
    [[EGOCache currentCache] clearCache];
    
    NSLog(@"Nhay vao view Did Load - Khoi tao");

    [self.tableView setBackgroundColor:[UIColor blackColor]];
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    if (photoStreams==nil) {
        photoStreams=[[NSMutableArray alloc] init];
    }
        //[self getGridPhotoList];
    _currPage=1;    
      
       
    
}
-(void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.hidden=YES;
    if (isChange==YES) {
        [photoStreams removeAllObjects];
        if ([photoStreams count]==0) {
            NSLog(@"tag String %@",tagSetting);
            NSString *link=[self generateURLFromUserId:@"1d6311db-6a2e-4362-a3c3-2a7a7814f7a4" tag:tagSetting page:_currPage];
            NSURL *url = [NSURL URLWithString:link];
            ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
            [request setDelegate:self];
            [request startAsynchronous];
        }
        isChange=NO;
    }
    
   
  
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Network error" message:@"Lỗi kết nối mạng. Xin vui lòng thử lại" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
       
    // Use when fetching binary data
    NSData *responseData = [request responseData];
    SBJsonParser *parser=[[SBJsonParser alloc] init];
    NSString *jsonString=[[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] autorelease];
    NSDictionary *status=(NSDictionary *)[parser objectWithString:jsonString error:nil] ;
   
          
    if ([status objectForKey:@"is_success"]!=0) {//Load photo to array if success
        NSArray *array=[status objectForKey:@"photo"];
        
        [photoStreams addObjectsFromArray:array];
        NSLog(@"\n Photo count:%i",[array count]);
        
        self.currPage++;
        NSLog(@"Done load data page %d",_currPage);
        [self.tableView reloadData];
    } else {
        if (_currPage==0) { //No data
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Thong bao" message:@"Co loi xay ra" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
        }
        
        
    }
 
    self.isParseJSON=YES;
    
    
    _isLoadingDataNextPage=NO;
    
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
   NSLog(@"Nhay vao view Did UnLoad");
    //self.photoStreams=nil;
    photoStreams=nil;
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void)buttonPress : (EGOImageButton *) button{
    
    if (detailView==nil) {
        detailView=[[DetailViewController alloc] init];
        
    }
    
    detailView.photoId=button.photoId;
    [[EGOCache currentCache] clearCache];
    
    [detailView.tableView reloadData];
    
    [self.navigationController pushViewController:detailView animated:YES];
    self.navigationController.navigationBar.hidden=NO;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (isParseJSON==YES) {
        return ([photoStreams count]/4);
    } else {
            return 6;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
        CustomGridCell *cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier];
    NSInteger row=[indexPath row];   
    if (cell == nil) {
        cell =[[CustomGridCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:SimpleTableIdentifier withStyle:row];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }  
    
         
    NSMutableArray *dataArray=[[[NSMutableArray alloc] init] autorelease];
    
    for (int i=0;i<4;i++) {
        if ((row*4+i)<([photoStreams count])) {
            NSDictionary *photo=[photoStreams objectAtIndex:4*row+i];
            [dataArray addObject:photo];            
        }
    }   
    [cell setCellsData:dataArray];
    
    return cell;
}
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 75;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
}
- (void)scrollViewDidScroll:(UIScrollView *)aScrollView {
    CGPoint offset = aScrollView.contentOffset;
    CGRect bounds = aScrollView.bounds;
    CGSize size = aScrollView.contentSize;
    UIEdgeInsets inset = aScrollView.contentInset;
    float y = offset.y + bounds.size.height - inset.bottom;
    float h = size.height;
    // NSLog(@"offset: %f", offset.y);   
    // NSLog(@"content.height: %f", size.height);   
    // NSLog(@"bounds.height: %f", bounds.size.height);   
    // NSLog(@"inset.top: %f", inset.top);   
    // NSLog(@"inset.bottom: %f", inset.bottom);   
    // NSLog(@"pos: %f of %f", y, h);
    
    float reload_distance = 60;
    if(y > h + reload_distance) {
        if (_isLoadingDataNextPage==NO) {
            
            //goi ham load data
            _isLoadingDataNextPage=YES;
            NSString *link=[self generateURLFromUserId:@"1d6311db-6a2e-4362-a3c3-2a7a7814f7a4" tag:@"cat" page:_currPage];
            NSURL *url = [NSURL URLWithString:link];
            ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
            [request setDelegate:self];
            [request startAsynchronous];
        }
    }
    
    
}
@end
